<template>
  <div class="exam-creator-hub">
    <div class="creator-content-wrapper">
      <div class="stepper-container">
        <el-steps :active="activeStep" finish-status="success" align-center>
          <el-step title="配置试卷" :icon="EditPen" />
          <el-step title="预览 & 发布" :icon="View" />
          <el-step title="完成" :icon="CircleCheck" />
        </el-steps>
      </div>

      <transition name="fade" mode="out-in">
        <div v-if="step === 1" class="step-content-wrapper">
          <div class="creation-workspace">
            <div class="config-panel">
              <h2 class="panel-title">
                <el-icon><Tools /></el-icon>
                <span>试卷生成器</span>
              </h2>
              <el-form :model="examConfig" label-position="top" class="exam-config-form">
                <el-form-item label="试卷主题/主要知识点">
                  <el-input
                    v-model="examConfig.description"
                    placeholder="例如: 初中二年级关于勾股定理的数学测验"
                    size="large"
                  />
                </el-form-item>

                <el-row :gutter="20">
                   <el-col :span="12">
                      <el-form-item label="选择题数量">
                          <el-input-number v-model="examConfig.mcqCount" :min="0" :max="50" style="width: 100%;" size="large"/>
                      </el-form-item>
                   </el-col>
                   <el-col :span="12">
                      <el-form-item label="判断题数量">
                          <el-input-number v-model="examConfig.tfqCount" :min="0" :max="50" style="width: 100%;" size="large"/>
                      </el-form-item>
                   </el-col>
                </el-row>

                <el-form-item label="整体难度">
                   <el-slider v-model="examConfig.difficulty" :marks="difficultyMarks" :step="25" show-stops />
                </el-form-item>

                <div class="form-spacer"></div>

                <el-form-item class="action-button-container">
                   <el-button
                      class="generate-button"
                      type="primary"
                      size="large"
                      @click="handleGenerateExam"
                      :loading="isLoading"
                      :disabled="isGenerateButtonDisabled"
                    >
                     <el-icon><MagicStick /></el-icon>
                     <span>{{ isLoading ? 'AI正在努力出题中...' : '启动智能生成' }}</span>
                   </el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="blueprint-panel">
               <div class="blueprint-header">
                  <h3 class="blueprint-title">
                      <el-icon><Document /></el-icon>
                      <span>试卷蓝图</span>
                  </h3>
                  <el-tag effect="light" round>实时预览</el-tag>
              </div>
              <div class="blueprint-body">
                  <p class="blueprint-item main-topic">
                      <span class="label">试卷主题</span>
                      <span class="value placeholder" v-if="!examConfig.description">待您输入试卷主题...</span>
                      <span class="value" v-else>{{ examConfig.description }}</span>
                  </p>
                  <el-divider />
                  <div class="stats-grid">
                      <div class="stat-item">
                          <span class="stat-value">{{ totalQuestions }}</span>
                          <span class="stat-label">题目总数</span>
                      </div>
                       <div class="stat-item">
                          <span class="stat-value">{{ examConfig.mcqCount }}</span>
                          <span class="stat-label">选择题</span>
                       </div>
                       <div class="stat-item">
                          <span class="stat-value">{{ examConfig.tfqCount }}</span>
                          <span class="stat-label">判断题</span>
                       </div>
                  </div>
                  <el-divider />
                  <div class="difficulty-display">
                      <span class="label">预设难度</span>
                      <el-progress :percentage="examConfig.difficulty + 1" :stroke-width="12" :format="() => difficultyText" color="#67C23A" />
                  </div>
              </div>
            </div>
          </div>
        </div>
      </transition>
      
      <transition name="fade">
        <div v-if="isLoading" class="loading-screen">
            <div class="loading-container">
                <div class="ai-animator">
                    <div class="corner corner-tl"></div>
                    <div class="corner corner-tr"></div>
                    <div class="corner corner-br"></div>
                    <div class="corner corner-bl"></div>
                    <el-icon class="center-icon"><MagicStick /></el-icon>
                </div>
                <h2 class="loading-title">智能引擎启动</h2>
                <p class="loading-subtitle">正在为您构建试卷，请稍候...</p>
            </div>
        </div>
      </transition>
    </div>

    <transition name="fade" mode="out-in">
      <div v-if="step === 2" class="creator-content-wrapper">
         <div class="preview-header">
            <div>
              <h2 class="preview-title">试卷预览 & 发布</h2>
              <p class="preview-subtitle">请仔细核对AI生成的题目，并设置考试时长后进行发布。</p>
            </div>
            <el-button @click="resetProcess" :icon="RefreshLeft" size="large">返回修改</el-button>
        </div>
        <div class="preview-layout">
            <div class="exam-preview-content">
              <h3 class="exam-title">{{ generatedExam.title }}</h3>
              <div v-for="(q, index) in generatedExam.questions" :key="index" class="question-block-v2">
                <p class="question-text">
                  <span class="question-index">{{ index + 1 }}.</span>
                  <el-tag size="small" effect="plain" class="question-type-tag">
                    {{ q.type === 'multiple-choice' ? '选择题' : '判断题' }}
                  </el-tag>
                  {{ q.question }}
                  <el-tag size="small" type="info" round class="topic-tag">{{ q.topic }}</el-tag>
                </p>
                <ul v-if="q.options" class="options-list-v2">
                  <li v-for="(option, key) in q.options" :key="key">
                    <span class="option-key">{{ key }}</span>
                    <span class="option-value">{{ option }}</span>
                  </li>
                </ul>
                <div class="answer-reveal">
                  <el-icon><Key /></el-icon>
                  <span>正确答案: <strong>{{ q.answer }}</strong></span>
                </div>
              </div>
            </div>
            <div class="publish-controls">
                <h4 class="publish-title">发布设置</h4>
                <el-form label-position="top">
                    <el-form-item label="设置考试时长 (分钟)">
                         <el-input-number v-model="publishForm.durationInMinutes" :min="1" :max="180" style="width: 100%" size="large"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="large" @click="handlePublishExam" :loading="isPublishing" class="publish-button">
                          <el-icon><Promotion /></el-icon>
                          <span>{{ isPublishing ? '发布中...' : '确认并立即发布' }}</span>
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
      </div>
    </transition>

    <transition name="fade" mode="out-in">
      <div v-if="step === 3" class="creator-content-wrapper">
        <el-result
            icon="success"
            title="考试发布成功！"
            :sub-title="`《${generatedExam.title}》已发布，考试时长${publishForm.durationInMinutes}分钟。`"
        >
            <template #extra>
                <el-button type="primary" @click="resetProcess" size="large">创建新试卷</el-button>
                <el-button @click="$router.push({ name: 'TeacherExamList' })" size="large">查看试卷列表</el-button>
            </template>
        </el-result>
      </div>
    </transition>
  </div>
</template>

<script setup>
// The script content remains exactly as you originally provided.
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import examService from '../../services/examService'; // Assuming service path is correct
import { useMascotStore } from '../../stores/mascotStore'; // Assuming store path is correct
import { 
  Tools, 
  MagicStick, 
  Document, 
  RefreshLeft, 
  Key, 
  EditPen, 
  View, 
  CircleCheck,
  Promotion
} from '@element-plus/icons-vue';

const mascot = useMascotStore();
const step = ref(1);
const isLoading = ref(false);
const isPublishing = ref(false);

const examConfig = reactive({
  description: '',
  mcqCount: 5, 
  tfqCount: 2, 
  difficulty: 50,
});

const difficultyMarks = reactive({
  0: '简单',
  25: '适中',
  50: '中等',
  75: '较难',
  100: '困难'
});

const generatedExam = ref(null);
const publishForm = ref({
  durationInMinutes: 60,
});

const activeStep = computed(() => step.value - 1);
const totalQuestions = computed(() => examConfig.mcqCount + examConfig.tfqCount);
const isGenerateButtonDisabled = computed(() => !examConfig.description.trim() || totalQuestions.value === 0);

const difficultyText = computed(() => {
    const d = examConfig.difficulty;
    if (d < 25) return '简单';
    if (d < 50) return '适中';
    if (d < 75) return '中等';
    if (d < 100) return '较难';
    return '困难';
});

onMounted(() => {
    const examplePrompt = '一份关于《高等数学》中“极限与连续”章节的期中测试';
    
    setTimeout(() => {
        mascot.show('进入了智能组卷页面！<br>一个好的描述能让AI更懂你。要不要试试这个例子？', {
            mood: 'idle',
            buttons: [
                { 
                    text: '帮我试试', 
                    action: () => {
                        examConfig.description = examplePrompt;
                        mascot.show('太棒了！现在点击下方的“启动智能生成”按钮，见证奇迹吧！', { mood: 'happy' });
                    } 
                },
            ]
        });
    }, 600);
});

const handleGenerateExam = async () => {
  if (isGenerateButtonDisabled.value) {
    ElMessage.warning('请填写试卷主题并至少选择一种题型');
    return;
  }
  mascot.hide();
  isLoading.value = true;
  
  const detailedPrompt = `请为我创建一份关于“${examConfig.description}”的测试。
要求如下：
1. 包含 ${examConfig.mcqCount} 道选择题。
2. 包含 ${examConfig.tfqCount} 道判断题。
3. 试卷的整体难度请控制在“${difficultyText.value}”水平。`;
  
  try {
    // Adding an artificial delay to demonstrate the beautiful new loader
    await new Promise(resolve => setTimeout(resolve, 4000)); 
    const data = await examService.generateExam(detailedPrompt);
    generatedExam.value = data;
    step.value = 2;
    ElMessage.success('试卷已智能生成，请预览！');
  } catch (error) {
    ElMessage.error(error.message || '生成试卷失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

const handlePublishExam = async () => {
    if(!generatedExam.value || !generatedExam.value.id) return;
    isPublishing.value = true;
    try {
        await examService.publishExam(generatedExam.value.id, publishForm.value.durationInMinutes);
        step.value = 3;
    } catch (error) {
        ElMessage.error(error.message || '发布考试失败');
    } finally {
        isPublishing.value = false;
    }
};

const resetProcess = () => {
    step.value = 1;
    generatedExam.value = null;
}
</script>

<style scoped>
/* --- General & Transitions --- */
.exam-creator-hub {
  padding: 32px 24px;
  background-color: #f9fafb; 
  min-height: 85vh;
}

.creator-content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.4s ease-in-out;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* --- Stepper --- */
.stepper-container {
  margin-bottom: 32px;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  border: 1px solid #eef2f7;
}

/* --- Step 1: Creation Workspace --- */
.creation-workspace {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 32px;
  position: relative;
  transition: filter 0.3s ease;
}

.creation-workspace.generating {
  filter: blur(4px);
}

.config-panel, .blueprint-panel {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px 32px;
  border: 1px solid #eef2f7;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
}

.panel-title, .blueprint-title {
  display: flex;
  align-items: center;
  font-size: 1.3rem;
  font-weight: 600;
  color: #34495e;
  margin-bottom: 24px;
}
.panel-title .el-icon, .blueprint-title .el-icon {
  margin-right: 12px;
  color: var(--el-color-primary);
}

.exam-config-form {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}
.form-spacer {
  flex-grow: 1;
}
.exam-config-form .el-form-item {
  margin-bottom: 22px;
}

.generate-button {
  width: 100%;
  height: 52px;
  font-size: 1.1rem;
  font-weight: 500;
}
.generate-button .el-icon {
  margin-right: 8px;
}

/* --- Step 1: Blueprint Panel --- */
.blueprint-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #eef2f7;
  margin-bottom: 24px;
}
.blueprint-body {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  justify-content: center;
}
.blueprint-item.main-topic {
  font-size: 1.1rem;
}
.blueprint-item .label {
  color: #7f8c8d;
  display: block;
  margin-bottom: 8px;
}
.blueprint-item .value {
  font-weight: 500;
  color: #2c3e50;
  line-height: 1.5;
}
.blueprint-item .placeholder {
  font-style: italic;
  color: #bdc3c7;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  text-align: center;
  margin: 24px 0;
}
.stat-item .stat-value {
  display: block;
  font-size: 2.5rem;
  font-weight: bold;
  color: var(--el-color-primary);
}
.stat-item .stat-label {
  font-size: 0.9rem;
  color: #7f8c8d;
}

.difficulty-display .label {
  color: #7f8c8d;
  margin-bottom: 12px;
  display: block;
}

/* --- Step 2 & 3 Styles --- */
.preview-header {
  display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;
}
.preview-title { font-size: 1.8rem; font-weight: 600; color: #2c3e50; margin: 0; }
.preview-subtitle { font-size: 1rem; color: #7f8c8d; margin-top: 4px; }

.preview-layout {
  display: grid; grid-template-columns: 1fr 340px; gap: 24px; align-items: flex-start;
}

.exam-preview-content, .publish-controls {
  background-color: #fff; border-radius: 12px; border: 1px solid #eef2f7; padding: 24px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}
.exam-preview-content {
  padding: 16px 24px; max-height: 70vh; overflow-y: auto;
}
.exam-title { text-align: center; font-size: 1.8rem; font-weight: bold; margin-bottom: 32px; }
.question-block-v2 { margin-bottom: 24px; padding-bottom: 24px; border-bottom: 1px dashed #dee2e6; }
.question-block-v2:last-child { border-bottom: none; }

.question-text { font-size: 1.05rem; line-height: 1.7; color: #34495e; margin-bottom: 16px; }
.question-index { font-weight: bold; margin-right: 8px; }
.question-type-tag { margin-right: 8px; }
.topic-tag { margin-left: 8px; }

.options-list-v2 { list-style: none; padding: 0; margin: 0 0 0 28px; display: flex; flex-direction: column; gap: 12px; }
.options-list-v2 li { display: flex; align-items: center; }
.option-key {
    display: flex; align-items: center; justify-content: center;
    width: 28px; height: 28px; border: 1px solid #bdc3c7; border-radius: 50%;
    margin-right: 12px; font-weight: 600; color: #34495e; flex-shrink: 0;
}
.option-value { color: #34495e; }

.answer-reveal {
  margin-top: 16px; padding: 8px 12px; background-color: #eafaf1; border: 1px solid #b8e9d1;
  border-radius: 6px; color: #2e7d32; font-size: 0.95rem; display: inline-flex; align-items: center;
}
.answer-reveal .el-icon { margin-right: 8px; color: #2ecc71; }
.answer-reveal strong { margin-left: 4px;}

.publish-controls { position: sticky; top: 20px; }
.publish-title { text-align: center; font-size: 1.3rem; font-weight: 600; margin-top: 0; margin-bottom: 24px; }
.publish-button { width: 100%; height: 48px; font-size: 1.1rem; }
.publish-button .el-icon { margin-right: 8px; }

.el-result { padding: 60px 32px; }

/* --- Responsive Adjustments --- */
@media (max-width: 992px) {
  .creation-workspace, .preview-layout {
    grid-template-columns: 1fr;
  }
}


/* --- [NEW] Advanced Fullscreen Loading Animation --- */
.loading-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-container {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.ai-animator {
  position: relative;
  width: 120px;
  height: 120px;
  margin-bottom: 40px;
  animation: rotate-animator 4s linear infinite;
}

.center-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 40px;
  color: var(--el-color-primary);
  /* Counter-rotate the icon and add a pulse */
  animation: counter-rotate-animator 4s linear infinite, 
             pulse-icon 2s ease-in-out infinite;
}

.corner {
  position: absolute;
  width: 30px; /* Increased size */
  height: 30px; /* Increased size */
  border-color: var(--el-color-primary-light-3);
  border-style: solid;
  /* Corners will breathe in and out */
  animation: shrink-corners 2s ease-in-out infinite;
}

.corner-tl {
  top: -4px; left: -4px;
  border-width: 4px 0 0 4px;
  border-top-left-radius: 10px;
}
.corner-tr {
  top: -4px; right: -4px;
  border-width: 4px 4px 0 0;
  border-top-right-radius: 10px;
}
.corner-br {
  bottom: -4px; right: -4px;
  border-width: 0 4px 4px 0;
  border-bottom-right-radius: 10px;
}
.corner-bl {
  bottom: -4px; left: -4px;
  border-width: 0 0 4px 4px;
  border-bottom-left-radius: 10px;
}

.loading-title {
  font-size: 1.7rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.loading-subtitle {
  font-size: 1rem;
  color: #7f8c8d;
}

/* --- Keyframe Animations --- */

/* Main container rotation */
@keyframes rotate-animator {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Keeps the icon upright */
@keyframes counter-rotate-animator {
  from { transform: translate(-50%, -50%) rotate(0deg); }
  to { transform: translate(-50%, -50%) rotate(-360deg); }
}

/* Icon pulse effect for a "living" feel */
@keyframes pulse-icon {
  0%, 100% { transform: translate(-50%, -50%) rotate(0deg) scale(1); opacity: 0.9; }
  50% { transform: translate(-50%, -50%) rotate(-180deg) scale(1.15); opacity: 1; }
}

/* Corner brackets breathing effect */
@keyframes shrink-corners {
  0%, 100% {
    width: 30px;
    height: 30px;
    border-color: var(--el-color-primary-light-3);
  }
  50% {
    width: 20px;
    height: 20px;
    border-color: var(--el-color-primary);
  }
}
</style>